<template>
  <div class="queue-stats-tab">
    <!-- 搜索卡片 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>

        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="环境">
                <el-select
                  v-model="searchForm.env_id"
                  placeholder="选择环境"
                  clearable
                  style="width: 200px"
                  @change="handleEnvChange"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="env in store.envConfigsList"
                    :key="env.id"
                    :label="env.env_name"
                    :value="env.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="队列Key">
                <el-input
                  v-model="searchForm.queue_key"
                  placeholder="队列Key"
                  clearable
                  style="width: 250px"
                />
              </el-form-item>

              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  :shortcuts="dateShortcuts"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 400px"
                  :teleported="true"
                  popper-class="datetime-picker-popper"
                  :clearable="true"
                  @change="handleDateRangeChange"
                />
              </el-form-item>
            </div>

            <div class="search-form-actions">
              <el-button type="info" plain @click="toggleStats">
                <el-icon>
                  <component :is="showStats ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ showStats ? '隐藏统计' : '显示统计' }}
              </el-button>
              <el-button type="danger" @click="$router.push('/redis-task-monitor/queue-config')" plain>
                <el-icon><Setting /></el-icon>
                队列监控配置
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 统计摘要卡片 -->
    <div v-if="store.queueStatsSummary && Object.keys(store.queueStatsSummary).length > 0" v-show="showStats" class="stats-section">
      <el-card shadow="hover" class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">总记录数</div>
            <div class="stat-value">{{ store.queueStatsSummary.total_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均队列长度</div>
            <div class="stat-value">{{ formatNumber(store.queueStatsSummary.avg_length || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最大队列长度</div>
            <div class="stat-value success">{{ formatNumber(store.queueStatsSummary.max_length || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最小队列长度</div>
            <div class="stat-value info">{{ formatNumber(store.queueStatsSummary.min_length || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均增长率(%)</div>
            <div class="stat-value">{{ formatDecimal(store.queueStatsSummary.avg_growth_rate || 0) }}%</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均失败率(%)</div>
            <div class="stat-value warning">{{ formatDecimal(store.queueStatsSummary.avg_failed_rate || 0) }}%</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 趋势图表卡片 -->
    <div class="chart-section" v-if="showChart">
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>队列趋势图表</span>
            <el-button
              type="success"
              size="small"
              class="refresh-btn"
              @click="loadTrendData"
              :loading="trendLoading"
            >
              <el-icon><Refresh /></el-icon>
              刷新图表
            </el-button>
          </div>
        </template>
        <div ref="trendChartRef" style="width: 100%; height: 400px;"></div>
      </el-card>
    </div>

    <!-- 表格卡片 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>队列统计数据列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="store.queueStatsLoading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button type="info" @click="handleLoadSummary" size="small">
                <el-icon><DataAnalysis /></el-icon>
                加载统计
              </el-button>
              <el-button type="info" size="small" plain @click="toggleChart">
                <el-icon>
                  <component :is="showChart ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ showChart ? '隐藏图表' : '显示图表' }}
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper clickable" @click="togglePagination">
                  <span class="page-count">本页 {{ store.queueStats.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">
                    {{ store.queueStatsPage }}/{{ Math.ceil(store.queueStatsTotal / store.queueStatsPageSize) || 1 }}
                  </span>
                  <el-icon class="pagination-toggle-icon">
                    <ArrowUp v-if="paginationVisible" />
                    <ArrowDown v-else />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>

        <div class="table-container">
          <el-table
            :data="store.queueStats"
            class="enhanced-table"
            style="width: 100%"
            :height="600"
            table-layout="fixed"
            :stripe="false"
            :border="false"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable="custom" />
            <el-table-column prop="queue_key" label="队列Key" min-width="250" show-overflow-tooltip />
            <el-table-column prop="length" label="队列长度" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                {{ formatNumber(row.length || 0) }}
              </template>
            </el-table-column>
            <el-table-column prop="previous_length" label="上次长度" width="120" align="right">
              <template #default="{ row }">
                {{ formatNumber(row.previous_length || 0) }}
              </template>
            </el-table-column>
            <el-table-column prop="delta" label="增长数量" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                <span :class="getGrowthClass(row.delta)">
                  {{ formatNumber(row.delta || 0) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="growth_rate" label="增长率(%)" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                {{ formatDecimal(row.growth_rate || 0) }}%
              </template>
            </el-table-column>
            <el-table-column prop="failed_count" label="失败数量" width="120" align="right">
              <template #default="{ row }">
                {{ formatNumber(row.failed_count || 0) }}
              </template>
            </el-table-column>
            <el-table-column prop="total_count" label="总数量" width="120" align="right">
              <template #default="{ row }">
                {{ formatNumber(row.total_count || 0) }}
              </template>
            </el-table-column>
            <el-table-column prop="failed_rate" label="失败率(%)" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                <span :class="getFailedRateClass(row.failed_rate)">
                  {{ formatDecimal(row.failed_rate || 0) }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="collection_time" label="采集时间" width="180" sortable="custom" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleViewDetail(row)"
                      circle
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="store.queueStatsPage"
              v-model:page-size="store.queueStatsPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="store.queueStatsTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 队列统计详情对话框 -->
    <QueueStatsDetailDialog
      v-model="detailDialogVisible"
      :queue-stats="currentQueueStats"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue'
import {
  Search, Refresh, List, View, DataAnalysis, TrendCharts, Setting,
  ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import { useRedisTaskMonitorStore } from '@/stores/redisTaskMonitor'
import QueueStatsDetailDialog from './dialogs/QueueStatsDetailDialog.vue'
import { createLogger } from '@/utils/logger'
import * as echarts from 'echarts'

const componentLogger = createLogger('QueueStatsTab')
const store = useRedisTaskMonitorStore()

const searchForm = reactive({
  env_id: '',
  queue_key: ''
})

const dateRange = ref([])
const dateShortcuts = [
  {
    text: '最近1小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '最近6小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(end.getTime() - 6 * 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(end.getTime() - 24 * 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(end.getTime() - 7 * 24 * 3600 * 1000)
      return [start, end]
    }
  }
]
const paginationVisible = ref(false)
const detailDialogVisible = ref(false)
const currentQueueStats = ref(null)
const sortField = ref('collection_time')
const sortOrder = ref('desc')
const showChart = ref(false)
const showStats = ref(false)
const trendLoading = ref(false)
const trendChartRef = ref(null)
let trendChart = null

// 环境变化处理
const handleEnvChange = () => {
  // 环境变化时可以加载队列配置列表
}

// 时间范围变化处理
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    searchForm.start_time = dates[0]
    searchForm.end_time = dates[1]
  } else {
    searchForm.start_time = ''
    searchForm.end_time = ''
  }
}

// 格式化数字
const formatNumber = (num) => {
  if (num === null || num === undefined) return '0'
  return num.toLocaleString()
}

// 格式化小数
const formatDecimal = (num) => {
  if (num === null || num === undefined) return '0.00'
  return parseFloat(num).toFixed(2)
}

// 获取增长数量样式类
const getGrowthClass = (growthCount) => {
  if (growthCount > 0) return 'growth-positive'
  if (growthCount < 0) return 'growth-negative'
  return 'growth-zero'
}

// 获取失败率样式类
const getFailedRateClass = (failedRate) => {
  if (failedRate > 10) return 'failed-rate-high'
  if (failedRate > 5) return 'failed-rate-medium'
  return 'failed-rate-low'
}

// 搜索
const handleSearch = async () => {
  store.queueStatsPage = 1
  await fetchData()
  await fetchSummary()
  if (showChart.value) {
    await loadTrendData()
  }
}

// 重置
const handleReset = () => {
  searchForm.env_id = ''
  searchForm.queue_key = ''
  searchForm.start_time = ''
  searchForm.end_time = ''
  dateRange.value = []
  store.queueStatsPage = 1
  fetchData()
  fetchSummary()
  if (showChart.value) {
    loadTrendData()
  }
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 加载统计摘要
const handleLoadSummary = async () => {
  await fetchSummary()
}

// 切换图表显示
const toggleChart = () => {
  showChart.value = !showChart.value
  if (showChart.value) {
    nextTick(() => {
      initChart()
      loadTrendData()
    })
  } else {
    destroyChart()
  }
}

// 初始化图表
const initChart = () => {
  if (!trendChartRef.value) return
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
    window.addEventListener('resize', handleResize)
  }
}

// 销毁图表
const destroyChart = () => {
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
    window.removeEventListener('resize', handleResize)
  }
}

// 窗口大小变化处理
const handleResize = () => {
  if (trendChart) {
    trendChart.resize()
  }
}

// 加载趋势数据
const loadTrendData = async () => {
  if (!showChart.value) return
  
  try {
    trendLoading.value = true
    const params = {}
    
    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }
    
    if (searchForm.queue_key) {
      params.queue_key = searchForm.queue_key
    }
    
    if (searchForm.start_time) {
      params.start_time = searchForm.start_time
    }
    
    if (searchForm.end_time) {
      params.end_time = searchForm.end_time
    }
    
    params.limit = 100
    
    await store.fetchQueueStatsTrend(params)
    renderChart()
  } catch (error) {
    componentLogger.error('加载趋势数据失败', error)
  } finally {
    trendLoading.value = false
  }
}

// 渲染图表
const renderChart = () => {
  if (!trendChart || !store.queueStatsTrend || store.queueStatsTrend.length === 0) return
  
  const times = store.queueStatsTrend.map(item => item.time)
  const queueLengths = store.queueStatsTrend.map(item => item.length || 0)
  const growthRates = store.queueStatsTrend.map(item => item.growth_rate || 0)
  const failedRates = store.queueStatsTrend.map(item => item.failed_rate || 0)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['队列长度', '增长率(%)', '失败率(%)'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times,
      axisLabel: {
        rotate: 45,
        formatter: (value) => {
          if (value && value.length > 16) {
            return value.slice(11, 16) // HH:mm
          }
          return value
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '队列长度',
        position: 'left'
      },
      {
        type: 'value',
        name: '比率(%)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '队列长度',
        type: 'line',
        smooth: true,
        data: queueLengths,
        itemStyle: {
          color: '#409eff'
        }
      },
      {
        name: '增长率(%)',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: growthRates,
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '失败率(%)',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: failedRates,
        itemStyle: {
          color: '#f56c6c'
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const data = await store.fetchQueueStatsDetail(row.id)
    currentQueueStats.value = data
    detailDialogVisible.value = true
  } catch (error) {
    componentLogger.error('获取队列统计详情失败', error)
  }
}

// 排序
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
    fetchData()
  }
}

// 分页
const handleSizeChange = (size) => {
  store.queueStatsPageSize = size
  store.queueStatsPage = 1
  fetchData()
}

const handlePageChange = (page) => {
  store.queueStatsPage = page
  fetchData()
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const toggleStats = () => {
  showStats.value = !showStats.value
}

// 获取统计数据
const fetchSummary = async () => {
  try {
    const params = {}
    
    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }
    
    if (searchForm.queue_key) {
      params.queue_key = searchForm.queue_key
    }
    
    if (searchForm.start_time) {
      params.start_time = searchForm.start_time
    }
    
    if (searchForm.end_time) {
      params.end_time = searchForm.end_time
    }

    await store.fetchQueueStatsSummary(params)
  } catch (error) {
    componentLogger.error('获取队列统计摘要失败', error)
  }
}

// 获取数据
const fetchData = async () => {
  try {
    const params = {
      page: store.queueStatsPage,
      pageSize: store.queueStatsPageSize,
      sort: sortField.value,
      order: sortOrder.value
    }

    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }

    if (searchForm.queue_key) {
      params.queue_key = searchForm.queue_key
    }

    if (searchForm.start_time) {
      params.start_time = searchForm.start_time
    }

    if (searchForm.end_time) {
      params.end_time = searchForm.end_time
    }

    await store.fetchQueueStats(params)
  } catch (error) {
    componentLogger.error('获取队列统计数据列表失败', error)
  }
}

// 导出方法供父组件调用
defineExpose({
  fetchData
})

onMounted(async () => {
  // 加载环境列表
  await store.fetchEnvConfigsList()
  // 加载数据
  await fetchData()
  // 加载统计摘要
  await fetchSummary()
})

onUnmounted(() => {
  destroyChart()
})
</script>

<style scoped>
.queue-stats-tab {
  padding: 0;
}

.search-section {
  margin-bottom: 24px;
}

.stats-section {
  margin-bottom: 20px;
}

.chart-section {
  margin-bottom: 20px;
}

.stats-card,
.chart-card {
  border-radius: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.info {
  color: #409eff;
}

.stat-value.warning {
  color: #f56c6c;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  margin-top: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination-control-wrapper:hover {
  background-color: #f5f7fa;
}

.page-count {
  font-size: 12px;
  color: #606266;
}

.divider {
  width: 1px;
  height: 14px;
  background-color: #dcdfe6;
}

.pagination-info {
  font-size: 12px;
  color: #909399;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #909399;
}

.table-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.growth-positive {
  color: #67c23a;
}

.growth-negative {
  color: #f56c6c;
}

.growth-zero {
  color: #909399;
}

.failed-rate-high {
  color: #f56c6c;
  font-weight: 600;
}

.failed-rate-medium {
  color: #e6a23c;
}

.failed-rate-low {
  color: #67c23a;
}

.pagination-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s ease;
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
